package com.haiyou.dc.es.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author pc
 */
@Configuration
@Slf4j
public class ElasticsearchConfig {

    @Value("${elasticsearch.port}")
    private int clusterPort;
    @Value("${elasticsearch.cluster-name}")
    private String esClusterName;
    @Value("${elasticsearch.cluster-nodes}")
    private String esClusterNode;

    private List<InetSocketTransportAddress> list = new ArrayList<>();

    @Bean
    public Client client() throws UnknownHostException {
        log.info("---------------------------->初始化Elasticsearch配置------------------------>");
        log.info("clusterPort={},cluster-nodes={},clusterName={}---------------------------->", clusterPort, esClusterNode, esClusterName);

        //es集群配置（自定义配置） 连接自己安装的集群名称
        Settings settings = Settings.builder().put("cluster.name", esClusterName)
                .put("client.transport.sniff", true).build();
        PreBuiltTransportClient client = new PreBuiltTransportClient(settings);
        client.addTransportAddresses(getTransportAddresses());
        return client;
    }

    private InetSocketTransportAddress[] getTransportAddresses() throws UnknownHostException {
        if (StringUtils.isNotBlank(esClusterNode)) {
            String[] esClusterList = esClusterNode.split(",");
            for (String str : esClusterList) {
                InetSocketTransportAddress transportAddress = new InetSocketTransportAddress(InetAddress.getByName(str), clusterPort);
                list.add(transportAddress);
            }
        }
        return list.toArray(new InetSocketTransportAddress[list.size()]);
    }

}
